<template>
  <div class="p-2">
    <transition>
      <!-- 查询区 -->
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户名" prop="name">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
              class="w-200px!"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="name">
            <el-input
              v-model="queryParams.phoneNumber"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
              class="w-200px!"
            />
          </el-form-item>
          <el-form-item label="状态" prop="email">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="区域查询">
            <el-cascader
              :options="searchData.searchRegionTree"
              v-model="queryParams.regionId"
              clearable
              :props="regionManageCascaderProps"
              :show-all-levels="false"
              @change="handleSearchRegionChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item label="机构查询" prop="organizationArr">
            <el-cascader
              clearable
              v-model="queryParams.organizationId"
              :props="organizationCascaderProps"
              :options="searchData.searchOrganizationTree"
              :show-all-levels="false"
              @change="handleSearchOrganizationChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item label="注册时间" prop="age">
              <el-date-picker
                v-model="queryParams.time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleDateRangeChange"
              />
            </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
              v-hasPermi="['system:user:edit']"
            >
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
            >
              删除
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:import']"
            >
              导出
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-upload
              ref="upload"
              class="upload-demo"
              action="#"
              :limit="1"
              :on-change="beforeUpload"
              :on-exceed="handleExceed"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button
                  type="info"
                  plain
                  icon="Delete"
                  @click="handleImport"
                  v-hasPermi="['system:user:import']"
                >
                  导入
                </el-button>
              </template>
            </el-upload>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getUserList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column label="用户id" align="center" prop="id" />
        <el-table-column label="用户编号" align="center" prop="personnelCode" />

        <el-table-column label="手机号" align="center" prop="phoneNumber" />
        <el-table-column label="用户名" align="center" prop="userName" />
        <el-table-column label="昵称" align="center" prop="nickName" />
        <el-table-column label="机构" align="center" prop="organizationName" />
        <el-table-column label="岗位" align="center" prop="job" />
        <el-table-column label="创建时间" align="center" prop="createTime" />

        <el-table-column label="状态" prop="status" width="80">
          <template #default="{ row }: { row: SysUserVo }">
            <el-tag :type="UserStatusTypeMap.get(row.status ?? '') ?? 'info'">
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="140"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <span v-hasPermi="['system:user:edit']" class="ml-10px">
              <el-tooltip content="编辑" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
            <!-- <el-tooltip content="修改密码" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="FolderOpened"
                  @click="handleChangePWD(scope.row)"
                ></el-button>
              </el-tooltip> -->
            <span v-hasPermi="['system:user:remove']" class="ml-10px">
              <el-tooltip content="删除" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getUserList"
      />
    </el-card>

    <!-- 弹出框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="60%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        :model="currentDialogData"
        ref="dialogFormRef"
        :rules="rules"
        :inline="true"
        label-width="108px"
        class="dialogForm"
      >
        <el-row>
          <el-form-item label="用户名" prop="userName">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
              style="width: 220px"
            />
          </el-form-item>

          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.nickName"
              placeholder="请输入昵称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="超级管理员" v-if="isSuperAdmin">
            <el-select
              :disabled="
                DialogData.isDisabled || currentUserId === currentDialogData.id
              "
              v-model="currentDialogData.superAdmin"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.superAdminArr"
                :key="(item as any).value"
                :label="(item as any).label"
                :value="(item as any).value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="岗位" prop="job">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.job"
              placeholder="请输入岗位"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="用户编号" prop="job">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.personnelCode"
              placeholder="请输入用户编号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="参与审核">
            <el-select
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.examine"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.examineArr"
                :key="(item as any).value"
                :label="(item as any).label"
                :value="(item as any).value"
              />
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="状态" prop="status">
            <el-select
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusArr"
                :key="(item as any).value"
                :label="(item as any).label"
                :value="(item as any).value"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="审核角色" prop="identity">
              <el-select
                :disabled="DialogData.isDisabled"
                v-model="currentDialogData.identityList"
                clearable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in selectArr.identityArr"
                  :key="(item as any).id"
                  :label="(item as any).name"
                  :value="(item as any).id"
                />
              </el-select>
            </el-form-item> -->

          <el-form-item label="密码" prop="passWord">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.password"
              placeholder="请输入密码"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.phoneNumber"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.email"
              placeholder="请输入邮箱"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="性别" prop="sex">
            <el-select
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.sex"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.sexArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-tooltip
            :content="currentDialogData.organizationSelection"
            :disabled="currentDialogData.organizationSelection === ''"
            :enterable="false"
            placement="top"
            effect="light"
          >
            <el-form-item label="所属机构" prop="organizationId">
              <el-cascader
                ref="organizationCascader"
                :disabled="DialogData.isDisabled"
                v-model="currentDialogData.organizationId"
                clearable
                :props="organizationCascaderProps"
                :options="searchData.searchOrganizationTree"
                :show-all-levels="true"
                @change="dialogOrganizationChange"
              >
                <template #default="{ node }">
                  <el-tooltip
                    :content="node.label"
                    placement="top-start"
                    :enterable="false"
                  >
                    <span>{{ node.label }}</span>
                  </el-tooltip>
                </template>
              </el-cascader>
            </el-form-item>
          </el-tooltip>
        </el-row>

        <!--        <el-form-item label="管理区域" prop="regionDataScope">-->
        <!--          <el-cascader-->
        <!--            ref="regionManageCascader"-->
        <!--            :disabled="DialogData.isDisabled"-->
        <!--            v-model="currentDialogData.regionDataScope.allow"-->
        <!--            :options="searchData.searchRegionTree"-->
        <!--            clearable-->
        <!--            collapse-tags-->
        <!--            collapse-tags-tooltip-->
        <!--            :props="regionManageCascaderProps"-->
        <!--            @change="handleChange()"-->
        <!--          >-->
        <!--            <template #default="{ node }">-->
        <!--              <span>{{ node.label }}</span>-->
        <!--            </template>-->
        <!--          </el-cascader>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="管理机构" prop="organizationDataScope">-->
        <!--          <el-cascader-->
        <!--            ref="organizationManageCascader"-->
        <!--            v-model="currentDialogData.organizationDataScope.allow"-->
        <!--            clearable-->
        <!--            :disabled="DialogData.isDisabled"-->
        <!--            collapse-tags-->
        <!--            collapse-tags-tooltip-->
        <!--            :props="organizationManageCascaderProps"-->
        <!--            :options="searchData.searchOrganizationTree"-->
        <!--            @change="handleOrganizationChange"-->
        <!--          >-->
        <!--            <template #default="{ node }">-->
        <!--              <span>{{ node.label }}</span>-->
        <!--            </template>-->
        <!--          </el-cascader>-->
        <!--        </el-form-item>-->

        <el-row>
          <el-form-item class="dialogFooter">
            <el-button type="primary" icon="Search" @click="addSubmit">
              提交
            </el-button>
            <el-button icon="Refresh" @click="closeDialog">关闭</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- <el-dialog
        v-model="dialog.changePWD"
        :title="dialog.title"
        width="60%"
        center
        :show-close="false"
        :close-on-click-modal="false"
        @close="closeDialog"
      >
        <el-form
          :model="currentDialogData"
          ref="diologFormRef"
          :rules="rules"
          :inline="true"
          label-width="108px"
          class="dialogForm"
        >
          <el-form-item label="请输入旧密码" prop="userName">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="请输入新密码" prop="userName">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="请再次输入密码" prop="userName">
            <el-input
              :disabled="DialogData.isDisabled"
              v-model="currentDialogData.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
              style="width: 220px"
            />
          </el-form-item>
        </el-form>
      </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import {
  getUserList as getUserListApi,
  userAdd as userAddApi,
  getUserDetail as getUserDetailApi,
  updateUser as updateUserApi,
  deleteUser as deleteUserApi,
  getDefaultRegionTree as getDefaultRegionTreeApi,
  getOrganizationTree as getOrganizationTreeApi,
  importExcel as importExcelApi,
  changePassword as changePasswordApi,
} from "@/service/api/system/user";
import {
  SysUserVo,
  checkUser,
  RegionNode,
  SysUserInfoVo,
  OrganizationNode,
  InitUserDialogData,
} from "@/service/api/system/user/types";
import { ElForm } from "element-plus";
import { download } from "@/utils/request";
import { ref } from "vue";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { useUserStore } from "@/store/modules/user.ts";
import { to } from "await-to-js";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import {
  UserStatusMap,
  UserStatusTypeMap,
} from "@/maps/system/user/userStatusMap.ts";
import Pagination from "@/components/Pagination/index.vue";
import RightToolbar from "@/components/RightToolbar/index.vue";
import { convertTimeRange } from "@/utils/request.ts";


// uploadDOM实例对象
const upload = ref<UploadInstance>();

// 上传excel到后端
const importExcel = async (formData: any) => {
  const res = await importExcelApi(formData);
  console.log(res);
};

// 选择文件后上传
const beforeUpload = async (file: any) => {
  console.log(file);
  const formData = new FormData();
  formData.append("file", file.raw);
  await importExcel(formData);
};

/**
 * 选择文件超过一个时调用，触发重新选择文件
 * @param files
 */
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value?.handleStart(file);
  console.log(file);
};

// 列表数据
const userList = ref<SysUserVo[]>([]);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref(ElForm);
const dialogFormRef = ref(ElForm);
// 是否超级管理员
const isSuperAdmin = ref(false);
const currentUserId = ref();
const organizationCascader = ref();

// const regionManageCascader = ref();
// const organizationManageCascader = ref();
// 当前设置范围
// const currentRoleItem = ref({
//   regionDataScope: {
//     allow: [],
//     deny: [],
//   },
//   organizationDataScope: {
//     allow: [],
//     deny: [],
//   },
// });

const dialog = reactive({
  visible: false,
  changePWD: false,
  title: "",
});
const organizationCascaderProps = {
  checkStrictly: true,
  value: "id",
};
// const organizationManageCascaderProps = {
//   multiple: true,
//   value: "id",
// };
const regionManageCascaderProps = {
  checkStrictly: true,
  value: "id",
};

// 所有状态
const statusArr = reactive([
  {
    value: "2",
    label: "禁言",
  },
  {
    value: "0",
    label: "正常",
  },
  {
    value: "1",
    label: "停用",
  },
]);

// 初始数据
const initCurrentDialogData: InitUserDialogData = {
  userName: "",
  email: "",
  nickName: "",
  status: "0",
  phoneNumber: "",
  password: "",
  organizationId: "",
  sex: "",
  id: "",
  identityList: [],
  job: "",
  examine: false,
  superAdmin: false,
  loginDate: undefined,
  loginIp: undefined,
  regionDataScope: {
    allow: [],
    deny: [],
  },
  organizationDataScope: {
    allow: [],
    deny: [],
  },
  organizationSelection: "",
  personnelCode: "",
};

const initAddUserIdentity = {
  identityId: [],
  userId: "",
};

// 初始page参数
const initQueryParams = {
  pageNum: 1,
  pageSize: 10,
  phoneNumber: "",
  status: "",
  userName: "",
  time: "",
  regionId: "",
  organizationId: "",
  orderByColumn: "createTime",
  orderType: "desc",
  params: {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  },
};

// 参数，上方查询的数据
const searchData = reactive({
  queryParams: {
    ...initQueryParams,
  },
  // 获取组织参数
  organizationParams: {
    pageSize: 50,
    pageNum: 1,
    name: "",
  },
  organizationArr: [],
  rules: {
    phoneNumber: [{ required: true, message: "手机不能为空", trigger: "blur" }],
    userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    eMail: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    organizationId: [
      { required: true, message: "机构不能为空", trigger: "blur" },
    ],
    nickName: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
  },
  searchRegionTree: <RegionNode[]>[],
  searchOrganizationTree: <OrganizationNode[]>[],
});

// dialog数据
const DialogData = reactive({
  currentDialogData: { ...initCurrentDialogData },
  isDisabled: false,
  addUserIdentityBO: { ...initAddUserIdentity },
});
// dialog的select
const selectArr = reactive({
  // statusArr: [
  //   {
  //     value: "3",
  //     label: "未确认",
  //   },
  //   {
  //     value: "2",
  //     label: "禁言",
  //   },
  //   {
  //     value: "0",
  //     label: "正常",
  //   },
  //   {
  //     value: "1",
  //     label: "停用",
  //   },
  // ],
  sexArr: [
    {
      value: "0",
      label: "男",
    },
    {
      value: "1",
      label: "女",
    },
  ],
  identityArr: [],
  superAdminArr: [
    {
      value: false,
      label: "否",
    },
    {
      value: true,
      label: "是",
    },
  ],
  examineArr: [
    {
      value: false,
      label: "否",
    },
    {
      value: true,
      label: "是",
    },
  ],
});

const { queryParams, rules } = toRefs(searchData);
const { currentDialogData } = toRefs(DialogData);

/**
 * 获取用户基本信息
 */
const getUserInfo = () => {
  let userInfo = useUserStore();
  isSuperAdmin.value = userInfo.isSuperAdmin;
  currentUserId.value = userInfo.userId;
};

/**
 * 获取地区树
 */
const getRegionTree = async () => {
  const [err, res] = await to<BaseResponse<RegionNode[]>, any>(
    getDefaultRegionTreeApi(),
  );
  if (!err) {
    if (res && res.data) {
      console.log(res);
      searchData.searchRegionTree = res.data ?? [];
    }
  }
};

/**
 * 获取组织树
 */
const getOrganizationTree = async () => {
  const [err, res] = await to<BasePageResponse<OrganizationNode>, any>(
    getOrganizationTreeApi(),
  );

  if (!err) {
    searchData.searchOrganizationTree = res?.rows ?? [];
  }
};

/**
 * 获得用户列表数据
 */
const getUserList = async (): Promise<boolean> => {
  let result = false;

  loading.value = true;
  console.log(queryParams.value);
  const [err, res] = await to<BasePageResponse<SysUserVo>, any>(
    getUserListApi(queryParams.value),
  );
  if (!err) {
    console.log(res);
    total.value = Number(res?.total ?? 0);
    userList.value = res?.rows ?? [];

    userList.value.forEach((item: SysUserVo) => {
      item.statusMsg = UserStatusMap.get(item.status ?? "") ?? "未知";
    });

    loading.value = false;

    result = true;
  }
  loading.value = false;
  return result;
};

// 获取所有地区
// const getDefaultTree = async () => {
//   // 获取地区Tree
//   const { data } = await getDefaultRegionTreeApi();
//   searchData.searchRegionTree = data;
//   // 获取组织
//   // searchData.organizationParams
//   const res = await getOrganizationApi();
//   searchData.searchOrganizationTree = res.data;
// };


/**
 * 将选择的开始结束日期转换为后端需要的形式
 * @param value
 */
 const handleDateRangeChange = (value: [Date | null, Date | null]) => {
  console.log(value);
  queryParams.value.params = convertTimeRange(value);
};


/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  console.log(queryParams.value);
  queryParams.value.pageNum = 1;
  getUserList();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryParams.value = Object.assign({}, initQueryParams);
  handleQuery();
};

/**
 * 获取多选框选中数据
 */
const handleSelectionChange = (selection: checkUser[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/**
 * 处理新增按钮
 */
const handleAdd = async () => {
  dialog.visible = true;
  dialog.title = "新增用户";
};

/**
 * 处理编辑按钮
 */
const handleUpdate = async (row?: checkUser) => {
  const id = row?.id || ids.value[0];
  // loading.value = true;
  dialog.title = "编辑用户";
  showUserDetailDialog(id);
};

const showUserDetailDialog = async (userId: string) => {
  const [err, response] = await to<BaseResponse<SysUserInfoVo>, any>(
    getUserDetailApi(userId),
  );
  if (!err) {
    if (response && response.data) {
      currentDialogData.value = {
        ...initCurrentDialogData,
        ...response.data.user,
      };
      if (!currentDialogData.value.regionDataScope) {
        currentDialogData.value.regionDataScope = {
          allow: [],
          deny: [],
        };
      }
      if (!currentDialogData.value.organizationDataScope) {
        currentDialogData.value.organizationDataScope = {
          allow: [],
          deny: [],
        };
      }
      // 获取详细信息之后再打开dialog
      console.log(response.data, currentDialogData.value);
      dialog.visible = true;
      nextTick(() => {
        const selectedOrganizationNodes =
          organizationCascader.value.getCheckedNodes();
        if (selectedOrganizationNodes.length > 0) {
          currentDialogData.value.organizationSelection =
            selectedOrganizationNodes[0].pathLabels.join("/");
        }
      });
    }
  }
};

/**
 * 处理删除按钮
 */
const handleDelete = async (row?: checkUser) => {
  // 弹出删除确认框
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定删除选中的用户？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  } else if (confirm === "confirm") {
    loading.value = true;
    const _ids = row?.id || ids.value;
    const [err] = await to<BaseResponse<any>, any>(deleteUserApi(_ids));
    if (!err) {
      ElMessage({
        message: "用户删除成功",
        type: "success",
      });
      await getUserList();
    }
  }
  loading.value = false;
};

/**
 * 关闭dialog
 */
const closeDialog = () => {
  currentDialogData.value = Object.assign({}, initCurrentDialogData);
  currentDialogData.value.organizationDataScope.allow = [];
  currentDialogData.value.regionDataScope.allow = [];
  dialog.title = "";
  dialog.visible = false;
  loading.value = false;
  DialogData.isDisabled = false;
};

/**
 * 查看用户详情
 * @param row
 */
const handleDetail = async (row: any) => {
  DialogData.isDisabled = true;
  dialog.title = "用户详情";
  showUserDetailDialog(row.id);
};

// // 右侧编辑按钮
// const rightHandleUpdate = async (row: any) => {
//   // 保存用户id用于添加用户角色
//   addUserIdentityBO.value.userId = row.id;
//   dialog.title = "编辑用户";
//   // 当选择上方修改按钮时，ids只有一个数据
//   const [err, response] = await to(getUserDetailApi(row.id));
//   if (!err) {
//     currentDialogData.value = response.data.user;
//     if (!currentDialogData.value.regionDataScope) {
//       currentDialogData.value.regionDataScope = {
//         allow: [],
//         deny: [],
//       };
//     }
//     if (!currentDialogData.value.organizationDataScope) {
//       currentDialogData.value.organizationDataScope = {
//         allow: [],
//         deny: [],
//       };
//       // currentDialogData.value.identityList =
//       //   response.data.user.identityList.map((item: any) => {
//       //     return item.id;
//       //   });
//     }
//     console.log(currentDialogData.value);
//   }
//   dialog.visible = true;
// };

// // 右侧删除按钮
// const rightHandleDelete = async (row: any) => {
//   // 弹窗确认
//   const [err, confirm] = await to<string, string>(
//     ElMessageBox.confirm("确定删除该用户吗？", "提示", {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//       type: "warning",
//     }),
//   );
//   if (err === "cancel") {
//     // 弹出未删除提示
//     ElMessage({
//       type: "info",
//       message: "已取消删除",
//     });
//   } else if (confirm === "confirm") {
//     loading.value = true;
//
//     const [err] = await to(deleteUserApi(row.id));
//     if (err) {
//       ElMessage({
//         message: "用户删除失败",
//         type: "error",
//       });
//     } else {
//       ElMessage({
//         message: "用户删除成功",
//         type: "success",
//       });
//     }
//     await getUserList();
//   }
//   loading.value = false;
// };

// 新增用户的身份
// const addUserIdentity = async () => {
//   const res = await addUserIdentityApi()
// }

/**
 * 获取地区id
 * @param selectedData
 */
const handleSearchRegionChange = (selectedData: any) => {
  if (selectedData && selectedData.length > 0) {
    queryParams.value.regionId = selectedData[selectedData.length - 1];
  }
};

/**
 * 获取要查询的组织id
 * @param selectedData
 */
const handleSearchOrganizationChange = (selectedData: any) => {
  if (selectedData && selectedData.length > 0) {
    queryParams.value.organizationId = selectedData[selectedData.length - 1];
  }
};

/**
 * dialog获取组织id
 * @param selectedData
 */
const dialogOrganizationChange = (selectedData: any) => {
  console.log(organizationCascader.value.getCheckedNodes());
  if (selectedData && selectedData.length > 0) {
    currentDialogData.value.organizationId =
      selectedData[selectedData.length - 1];
    currentDialogData.value.organizationSelection = organizationCascader.value
      .getCheckedNodes()[0]
      .pathLabels.join("/");
  }
};

/**
 * 提交按钮
 */
const addSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 有id为更新
      if (currentDialogData.value.id) {
        currentDialogData.value.loginDate = null;
        currentDialogData.value.loginIp = null;
        // 若脱敏则删除电话字段
        if (currentDialogData.value.phoneNumber.includes("****")) {
          delete (currentDialogData.value as any).phoneNumber;
        }
        console.log(currentDialogData.value);
        if (currentDialogData.value.password != "") {
          const [err] = await to(changePasswordApi(currentDialogData.value));
          if (!err) {
            ElMessage({
              message: "密码修改成功",
              type: "success",
            });
          } else {
            ElMessage({
              message: "密码修改失败",
              type: "error",
            });
          }
        }

        const [err] = await to<BaseResponse<any>, any>(
          updateUserApi(currentDialogData.value),
        );
        if (!err) {
          dialog.visible = false;
          ElMessage({
            message: "用户修改成功",
            type: "success",
          });
          getUserList();
        }
      }
      // 无id为新增
      else {
        console.log(currentDialogData.value);

        const [err] = await to<BaseResponse<any>, any>(
          userAddApi(currentDialogData.value),
        );

        if (!err) {
          dialog.visible = false;
          ElMessage({
            message: "用户添加成功",
            type: "success",
          });
          getUserList();
        }
      }
    }
  });
};

/**
 * 处理导出按钮
 */
const handleExport = () => {
  download(
    "/system/user/export",
    { ...queryParams.value },
    `demo_${new Date().getTime()}.xlsx`,
  );
};

// 上传到oss

/**
 * 处理导入按钮
 */
const handleImport = () => {
  // TODO: 实现文件导入用户
};

onMounted(async () => {
  // await getDefaultTree();
  await getRegionTree();
  await getOrganizationTree();
  await getUserList();
  await getUserInfo();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }

  .el-select {
    width: 219px;
  }
}

.dialogFooter {
  margin: 40px 0 0 450px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 100px;
  }
}
</style>
